package org.jmc.refmanager.domain.dao.jpa;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.jmc.refmanager.domain.dao.QueryParam;
import org.jmc.refmanager.domain.dao.UserDao;
import org.jmc.refmanager.domain.model.OrgUnit;
import org.jmc.refmanager.domain.model.User;
import org.jmc.refmanager.security.SecurityHelper;
import org.jmc.refmanager.util.ListUtil;

public class UserDaoImpl extends GenericDaoJpa<User, Integer> implements UserDao {
	
	public UserDaoImpl() {
		super(User.class);
	}

	@Override
	public User getByMatricule(String matricule) {
//		Util.assertNotNull(matricule);
		
		// TODO Ameliorer ce code pour eviter la creation d'une map !
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("matricule", matricule);
		
		@SuppressWarnings("unchecked")
		List<User> matchingUsers = super.findByNamedQueryAndNamedParams(User.GET_BY_MATRICULE, 
				params);
		if (matchingUsers != null && matchingUsers.size() > 1) {
			// Abnormal case, should not occur
			throw new IllegalArgumentException("Plus d'un utilisateur correspond à ce matricule");
		}
		
		return ListUtil.getFirstEvenIfNull(matchingUsers);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<User> findTeam(QueryParam queryParam, String teamLeader) {
//		User approver = this.getByMatricule(teamLeader);
//		Query query = createNamedQuery("select u1 from User u1 inner join User u2 on (u1.validationScope=u2.validationScope) where u2.matricule=?1");
		return super.findByNamedQuery(User.FIND_BY_OWNER, teamLeader);
//		return super.findAndPaging(queryParam, query);
	}

	@Override
	public List<User> findInScope(OrgUnit direction) {
		return find("select u from User u join u.role r where u.validationScope = ?1 AND r.name=?2", 
				direction, SecurityHelper.ROLE_APPROVER);
	}

}
